package brad.zimmerman.dungeon.game;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;
import java.util.Set;
import java.io.IOException;
import java.io.Serializable;
import java.lang.String;

import brad.zimmerman.dungeon.game.R.color;
import brad.zimmerman.dungeon.game.ClassAnimation.slopeAwesome;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.FloatMath;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

//The main class. Responsible for calling all of the other classes
public class ActivityDungeons extends Activity {
	public ClassGameStats playerStats;
	public static ClassGameStats passedPlayerStats;
	public static float bkVolume;
	public ClassDrawingHolder Draws = new ClassDrawingHolder();
	public ClassUnlockable unlock;
	public boolean returnedWithResults;
	ClassSoundObjects sounds;
	ClassBackgroundSound backgroundMusic;
	//private SoundPool soundPool;
	//private HashMap<Integer, Integer> soundsMap;
	ClassDatabaseAct database;
	scaleKeeper scale;
	int gauntletLevel;
	public int difficultySetting = 50;
	public static int numTiles = 20;
	public int width,height;
	public int [] dataBaseInfo;
	public int[] settings;
	public Point point;
	public float textScaler;
	//private GraphicScaling[] dScaler = new GraphicScaling[11];
	boolean destroySurface,runningBar,unlockAll;
	TypedValue value;
	
	public class scaleKeeper {
		private int scale;
		scaleKeeper(int scale){
			//int multiplier = height/800;
			this.scale = scale;
		}
		public int getScale(){
			return scale;
		}
	}
	
	/*public void scaleGraphics(){
		View v = findViewById(R.layout.wheel);
		System.out.println(scale);
		dScaler[0] = new GraphicScaling(getResources(),Draws.classImages,scale.getScale());
		dScaler[1] = new GraphicScaling(getResources(),Draws.shopImages,scale.getScale());
		dScaler[2] = new GraphicScaling(getResources(),Draws.creditImages,scale.getScale());
		dScaler[3] = new GraphicScaling(getResources(),Draws.raceImages,scale.getScale());
		dScaler[4] = new GraphicScaling(getResources(),Draws.levelImages,scale.getScale());
		dScaler[5] = new GraphicScaling(getResources(),Draws.floorImages,scale.getScale());
		dScaler[6] = new GraphicScaling(getResources(),Draws.gameImages,scale.getScale());
		dScaler[7] = new GraphicScaling(getResources(),Draws.modImages,scale.getScale());
		dScaler[8] = new GraphicScaling(getResources(),Draws.enemyImages,scale.getScale());
		dScaler[9] = new GraphicScaling(getResources(),Draws.glyphImages,scale.getScale());
		dScaler[10] = new GraphicScaling(getResources(),Draws.godImages,scale.getScale());
	}*/
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        point = new Point(getDisplaySize(getWindowManager().getDefaultDisplay()));
        width = point.x;
    	height = point.y;
    	textScaler = (int)Math.pow(width/240,2)-1;
        //System.out.println("Dimensions: " + point.x + ":" + point.y);
    	scale = new scaleKeeper((int) 2);
    	database = new ClassDatabaseAct(this);
    	sounds = new ClassSoundObjects(this);
    	backgroundMusic = new ClassBackgroundSound(this);
    	database.checkCreate();
    	destroySurface = false;
    	unlockAll = false;
    	runningBar = false;
    	returnedWithResults = false;
    	value = new TypedValue();
    	//scaleGraphics();
    	settings = database.returnScoreValues(0, -1, -1);
    	if (settings == null){
    		database.InsertDatabase(0, 0, 0, 0, numTiles, difficultySetting, (int) backgroundMusic.getVolume(), (int) sounds.getVolume());
    		settings = database.returnScoreValues(0, -1, -1);
    	}
    	unlock = new ClassUnlockable(returnLevel());
    	dataBaseInfo = new int[]{
        		database.returnTechValues("Shield"),
        		database.returnTechValues("Armor"),
        		database.returnTechValues("Helm"),
        		database.returnTechValues("Boots"),
        		database.returnTechValues("Gloves"),
        		database.returnTechValues("Staff"),
        		database.returnTechValues("Sword"),
        		database.returnTechValues("Mace"),
        		database.returnTechValues("Dice"),
        		database.returnTechValues("Scope"),
        		database.returnTechValues("Mining"),
        		database.returnTechValues("Refining"),
        		database.returnTechValues("Medicine"),
        		database.returnTechValues("Barter"),
        		database.returnTechValues("Cities"),
        		database.returnTechValues("Religion"),
        		database.returnTechValues("Ritual"),
        		database.returnTechValues("Knowledge")
        		};
    	unlock.setUsedClasses(returnUsedClasses());
    	unlock.setUsedLevels(returnUsedLevels());
    	numTiles = settings[4];
    	difficultySetting = settings[5];
    	backgroundMusic.setVolume((float) settings[6]);
    	sounds.setVolume((float) settings[7]);
    	//initializeSound();
    	sounds.init();
    	newGame(0,0,unlock.getLevel()+1);
    }
	
    @Override
	public void onDestroy(){
		super.onDestroy(); 
		backgroundMusic.stopBackground();
	}
	
    @Override
	public void onStop(){
		super.onStop(); 
		backgroundMusic.stopBackground();
	}
    
	@Override
	public void onPause(){
		super.onPause(); 
		backgroundMusic.stopBackground();
	}
	
	@Override
	public void onStart(){
		super.onStart(); 
		if(!backgroundMusic.running){
			backgroundMusic.setBackgoundNoiseTheme();
			backgroundMusic.playBackground();
		}
		settings = database.returnScoreValues(0, -1, -1);
		/*if(!database.levelPlayed()){
		if(!unlockAll && playerStats != null){
			newGame(playerStats.player_race, 
					unlock.returnNewGamePositionClasses(unlock.returnDescriptionClasses(),playerStats.player_class), 
					unlock.getLevel()+1);
		}else if (playerStats != null){
			newGame(playerStats.player_race, playerStats.player_class, playerStats.player_level);
		}else{
			newGame(0,0,unlock.getLevel()+1);
		}}*/
	}
	
	@Override
	public void onResume(){
		super.onResume(); 
		if(!backgroundMusic.running){
			backgroundMusic.setBackgoundNoiseTheme();
			backgroundMusic.playBackground();
		}
		settings = database.returnScoreValues(0, -1, -1);
		/*if(!database.levelPlayed()){
		if(!unlockAll && playerStats != null){
			newGame(playerStats.player_race, 
					unlock.returnNewGamePositionClasses(unlock.returnDescriptionClasses(),playerStats.player_class), 
					unlock.getLevel()+1);
		}else if (playerStats != null){
			newGame(playerStats.player_race, playerStats.player_class, playerStats.player_level);
		}else{
			newGame(0,0,unlock.getLevel()+1);
		}}*/
	}
	
	@SuppressLint("NewApi")
	private static Point getDisplaySize(final Display display) {
	    final Point point = new Point();
	    //try {
	    //    display.getSize(point);
	    //} catch (java.lang.NoSuchMethodError ignore) { // Older device
	        point.x = display.getWidth();
	        point.y = display.getHeight();
	    //}
	    return point;
	}
	
	public boolean[] returnUsedClasses(){
		boolean[] holder = new boolean[Draws.classImages.length];
		for(int i = 0; i < Draws.classImages.length;i++){
			holder[i] = database.returnClassUsed(i,database);
		}
		return holder;
	}
	
	public boolean[] returnUsedLevels(){
		boolean[] holder = new boolean[Draws.levelImages.length];
		for(int i = 1; i < Draws.levelImages.length+1;i++){
			holder[i-1] = database.returnLevelUsed(i,database);
		}
		return holder;
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.menu, menu);
        return true;
    }
	
	public String[] returnBothArrays(){
		return concatenateArrays(Draws.itemSuffixes, Draws.techSuffixes);
	}
	
	public void storeDataValues(){
		final String[] both = returnBothArrays();
		for(int i = 0;i<both.length;i++){
			database.InsertTech(both[i], dataBaseInfo[i]);
		}
	}
	
	public int randomNumber(int max){
		Random random = new Random(System.nanoTime());;
		//false means that the odds hit
		return (random.nextInt( max ));
	}
	
	public String composeTechs(){
		String temp = "";
		temp += "Shield:\n";
		temp += "Armor:\n";
		temp += "Helm:\n";
		temp += "Boots:\n";
		temp += "Gloves:\n";
		temp += "Staff:\n";
		temp += "Sword:\n";
		temp += "Mace:\n";
		temp += "Dice:\n";
		temp += "Scope:\n";
		temp += "Mining:\n";
		temp += "Refining:\n";
		temp += "Medicine:\n";
		temp += "Barter:\n";
		temp += "Cities:\n";
		temp += "Religion:\n";
		temp += "Ritual:\n";
		return temp;
	}
	
	public String composeTechLevelString(String[] Upgrade){
		String temp = "";
		temp += dataBaseInfo[0] + "\t" + Upgrade[0]+ "\n";
		temp += dataBaseInfo[1] + "\t" + Upgrade[1]+ "\n";
		temp += dataBaseInfo[2] + "\t" + Upgrade[2]+ "\n";
		temp += dataBaseInfo[3] + "\t" + Upgrade[3]+ "\n";
		temp += dataBaseInfo[4] + "\t" + Upgrade[4]+ "\n";
		temp += dataBaseInfo[5] + "\t" + Upgrade[5]+ "\n";
		temp += dataBaseInfo[6] + "\t" + Upgrade[6]+ "\n";
		temp += dataBaseInfo[7] + "\t" + Upgrade[7]+ "\n";
		temp += dataBaseInfo[8] + "\t" + Upgrade[8]+ "\n";
		temp += dataBaseInfo[9] + "\t" + Upgrade[9]+ "\n";
		temp += dataBaseInfo[10] + "\t" + Upgrade[10]+ "\n";
		temp += dataBaseInfo[11] + "\t" + Upgrade[11]+ "\n";
		temp += dataBaseInfo[12] + "\t" + Upgrade[12]+ "\n";
		temp += dataBaseInfo[13] + "\t" + Upgrade[13]+ "\n";
		temp += dataBaseInfo[14] + "\t" + Upgrade[14]+ "\n";
		temp += dataBaseInfo[15] + "\t" + Upgrade[15]+ "\n";
		temp += dataBaseInfo[16] + "\t" + Upgrade[16]+ "\n";
		return temp;
	}
	
	public void printActiveThreads(){
		Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

		Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
		
		for (Thread pieces: threadArray){
			//System.out.println(pieces.getName());
		}
	}
	/*
	public void initializeSound(){
		soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
        soundsMap = new HashMap<Integer, Integer>();
        //soundsMap.put(1, soundPool.load(this, R.raw.dungeoncomplete, 1));
        //soundsMap.put(2, soundPool.load(this, R.raw.boss_kill, 1));
        soundsMap.put(1, soundPool.load(this, R.raw.secretmana, 1));
	}
	
	public void playSound(int sound){
		AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
        float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        float volume = streamVolumeCurrent / streamVolumeMax;  
 
        soundPool.play(soundsMap.get(sound), volume, volume, 1, 0, 1.0f);
	}*/

	public int calculateLevel(int exp){
		int i = 1;
		while(((i*i)*500 + i*500)< exp){
			i++;
		}
		return i-1;
	}
	
	public int calculateProgress(int exp){
		int i = 1;
		int lower, higher;
		float percent;
		while(((i*i)*500 + i*500)< exp){
			i++;
		}
		lower = exp - (((i-1)*(i-1))*500 + (i-1)*500);
		higher = ((i*i)*500 + i*500) - (((i-1)*(i-1))*500 + (i-1)*500);
		percent = ((float)lower)/((float)higher);
		return (int) (percent*100);
	}
	
    public int returnLevelExp(int level){
    	return ((level*level)*500 + level*500);
    }
	
	public int[] determineGreater(int hRank, int hScore, int hStepsTaken, int hCompleted, 
			int hRank2, int hScore2, int hStepsTaken2, int hCompleted2){
		int[] holder = new int[4];
		if(hRank2 > hRank){holder[0] = hRank2;}
		else{holder[0] = hRank;}
		if(hScore2>hScore){holder[1] = hScore2;}
		else{holder[1] = hScore;}
		if(hStepsTaken2<hStepsTaken){holder[2] = hStepsTaken2;}
		else{holder[2] = hStepsTaken;}
		if(hCompleted2 == 1){holder[3] = 1;}
		else{holder[3] = hCompleted;}
		return holder;
	}
    
	public String getTitle(int level, int pClass, int pRace){
		return ("Level " + level +  " " + Draws.raceStrings[pRace] + " " +Draws.classStrings[pClass]);
	}
	
	public boolean allTechsFound(){
		for(int tech: dataBaseInfo){
			if(tech < 10){
				return false;
			}
		}
		return true;
	}
	
	public ClassStringandPictureHolder getRewards(int levelsGained, int upgradesGained){
		int pickedNumber;
		ClassStringandPictureHolder rewards = new ClassStringandPictureHolder();
		if(!allTechsFound()){
		for(int i = 0; i < levelsGained; i++){
			pickedNumber = randomNumber(17);
    		while(dataBaseInfo[pickedNumber]>=10){
    			pickedNumber = randomNumber(17);
    		}
    		dataBaseInfo[pickedNumber]++;
    		rewards.addPicture("Upgrade: " +returnBothArrays()[pickedNumber], 
    				Draws.getiArray().searchPicture(returnBothArrays()[pickedNumber]),
    				Draws.getiArray().searchDescription(returnBothArrays()[pickedNumber]));
		}
		}
    	storeDataValues();
    	
    	if(upgradesGained!=0){
    		
    		for(int i = 0; i < Draws.unlockLevels.length;i++){
    			if(Draws.unlockLevels[i] == unlock.getLevel()+1){
    				rewards.addPicture("Class: " +Draws.classStrings[i], 
    						Draws.getiArray().searchPicture(Draws.classStrings[i]),
    						Draws.getiArray().searchDescription(Draws.classStrings[i]));
    			}
    		}
    		if(unlock.getLevel()+2<Draws.levelStrings.length){
    			rewards.addPicture("Dungeon Level: " +Draws.levelStrings[unlock.getLevel()+2], 
    					Draws.getiArray().searchPicture(Draws.levelStrings[unlock.getLevel()+2]),
    					Draws.getiArray().searchDescription(Draws.levelStrings[unlock.getLevel()+2]));
    		}
    		if(unlock.getLevel()+1 > 0){
    		for(int i = 0; i < Draws.glyphUnlockLevels.length;i++){
    			if(Draws.glyphUnlockLevels[i] == unlock.getLevel()+2 && i != 2){
    				rewards.addPicture("Spell: " +Draws.glyphStrings[i], 
    						Draws.getiArray().searchPicture(Draws.glyphStrings[i]),
    						Draws.getiArray().searchDescription(Draws.glyphStrings[i]));
    			}
    		}
    		for(int i = 0; i < Draws.raceUnlockLevels.length;i++){
    			if(Draws.raceUnlockLevels[i] == unlock.getLevel()+1){
    				rewards.addPicture("Race: " +Draws.raceStrings[i], 
    						Draws.getiArray().searchPicture(Draws.raceStrings[i]),
    						Draws.getiArray().searchDescription(Draws.raceStrings[i]));
    			}
    		}
    		}
    	}
    	if(rewards.getSize() < 1){
    		rewards.addPicture("Medal: Participation", R.drawable.medal_part,"You tried, and really, that is all that matters");
    	}
    	if(returnLevelCount(unlock.getLevel()+1)>0){
    		rewards.addPicture("Next Level Progress", R.drawable.next_level,"Beat the current level with "+returnLevelCount(unlock.getLevel()+1)+" more classes to unlock the next tier");
    	}else{
    		rewards.addPicture("Next Level Progress", R.drawable.next_level,"Beat the next level with "+returnLevelCount(unlock.getLevel()+2)+" classes to unlock the next tier");
    	}
    	return rewards;
	}
	
	public void infoMenu(){
		final messageHolder tutorialMessages = new messageHolder(this,scale.getScale(),1);
		//System.out.println("InfoMenu is running");
		returnedWithResults = false;
		if(backgroundMusic.running && backgroundMusic.currentlyPlaying != -1){
			backgroundMusic.stopBackground();
		}
		if(!backgroundMusic.running){
			backgroundMusic.setBackgoundNoiseTheme();
			backgroundMusic.playBackground();
		}
		
		int[] scoresHolder;
		int[] databaseScores = database.getTempDatabaseValues();
		final Context gameContext = this;
		//final int max;
    	setContentView(R.layout.infomenu);
    	
    	GridView gridView = (GridView) findViewById(R.id.InfoGrid);
    	TextView text1 = (TextView) findViewById(R.id.textinfoa);
        TextView text2 = (TextView) findViewById(R.id.textinfob);
        TextView text3 = (TextView) findViewById(R.id.textinfoe);
        
        if(databaseScores[6] == 1){
        	if(gauntletLevel == 14){
        		text1.setTextColor(Color.MAGENTA);
        		text1.setText("Undefeatable!!!");
        	}else{
        		text1.setTextColor(Color.GREEN);
        		text1.setText("Victorious!");
        	}
        }else{
        	text1.setTextColor(Color.RED);
        	text1.setText("Game Over");
        }
        //text1.setTextSize(28);
        //text2.setTextSize(22);
        //text2.setTextColor(Color.CYAN);
        text2.setText("Rewards");
        
        //text3.setTextSize(22);
        //value.string = text1.toString();
 	   	//text1.setTextSize(TypedValue.COMPLEX_UNIT_PX, 28f);
 	    //value.string = text2.toString();
	   	//text2.setTextSize(TypedValue.COMPLEX_UNIT_PX, 26f);
	   	//value.string = text3.toString();
 	   	//text3.setTextSize(TypedValue.COMPLEX_UNIT_PX, 26f);
 	   	
 	   	
        text3.setTextColor(Color.YELLOW);
        text3.setText(getTitle(databaseScores[3],databaseScores[1],databaseScores[0]));
        int[] temp = database.returnScoreValues(databaseScores[0], databaseScores[1], databaseScores[2]);
        //System.out.println(temp);
        if (temp != null){
        	//This happens if there is something in the database
        	scoresHolder = determineGreater(temp[4], temp[5], temp[6],temp[7],
        			databaseScores[3], databaseScores[4], databaseScores[5], databaseScores[6]);
        }else{
        	//This is if the database is empty
        	scoresHolder = determineGreater(0, 0, 0, 0,databaseScores[3], databaseScores[4], databaseScores[5], databaseScores[6]);
        }
        
        //Nothing is saved in the middle of the gauntlet (except for experience)
        if(gauntletLevel == 14){
        	database.InsertDatabase((databaseScores[1]+1) * 100 + (databaseScores[2]+1), databaseScores[0], databaseScores[1], 
        			15, scoresHolder[0], scoresHolder[1], scoresHolder[2], scoresHolder[3]);
		}
        //There is no gauntlet here
        else if(gauntletLevel == 0){
        	database.InsertDatabase((databaseScores[1]+1) * 100 + (databaseScores[2]+1), databaseScores[0], databaseScores[1], 
        			databaseScores[2], scoresHolder[0], scoresHolder[1], scoresHolder[2], scoresHolder[3]);
        }

    	final ProgressBar progress = (ProgressBar) findViewById(R.id.progressBar1); 
    	final int startExperience = database.returnTechValues("Knowledge");
    	final int startLevel = calculateLevel(startExperience);
    	final boolean playerWon = (databaseScores[6] == 1)? true : false;
    	final int endExperience = startExperience+(databaseScores[4]);
    	final ClassStringandPictureHolder spHolder = new ClassStringandPictureHolder(getRewards((calculateLevel(endExperience) - calculateLevel(startExperience)),returnLevel()-unlock.getLevel()));
        gridView.setAdapter(new ClassGridAdapter(this,spHolder));
        gridView.setOnItemClickListener(
        	    new OnItemClickListener(){
					public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
						// TODO Auto-generated method stub
						//((Image)view.setSelected(!(Image)view.getSelected()));
						tutorialMessages.showSingleMessage(spHolder.getIndex(position).getTitle(), spHolder.getIndex(position).getDescription(), spHolder.getIndex(position).getPicture());
					}
        });
    	//System.out.println("Experience: " + startExperience + " : " + endExperience);
    	//final int endExperience = startExperience+(15000);
    	//final int endLevel = calculateLevel(endExperience);
    	database.InsertTech("Knowledge", endExperience);
    	unlock.setLevel(returnLevel());
    	unlock.setClassUsed(true, databaseScores[1]);
    	if(gauntletLevel != 0){
    		unlock.setLevelUsed(true, 15);
    	}else{
    		unlock.setLevelUsed(true, databaseScores[2]);
    	}
    	
        //text3.setTextSize(16);
        //text3.setTextColor(Color.YELLOW);
    	progress.setProgress(calculateProgress(startExperience));
        
    	//database.printDatabase();
        final Button button = (Button) findViewById(R.id.continue_button);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	Random random = new Random(System.currentTimeMillis());
            	//storeDataValues();
            	//If the player won the game and he is playing on gauntlet mode
            	if(playerWon && gauntletLevel != 0 && gauntletLevel < 14 && playerStats != null){
            			final int playerRace = random.nextInt( Draws.raceStrings.length );
            			final int playerClass = random.nextInt( Draws.classStrings.length );
                		playerStats = new 
                        		ClassGameStats(
                        		(width/(numTiles+1)),
                        		playerRace,
                        		playerClass,
                        		++gauntletLevel, dataBaseInfo,sounds,unlock.getLevel()+1,playerStats.difficulty);
                		passedPlayerStats = playerStats;
                    activityFunction(gameContext);
            	}
            	else if (playerStats != null){
            		if(!unlockAll){
            			newGame(playerStats.player_race, 
            					unlock.returnNewGamePositionClasses(unlock.returnDescriptionClasses(),playerStats.player_class), 
            					unlock.getLevel()+1);
            		}else{
            			newGame(playerStats.player_race, playerStats.player_class, playerStats.player_level);
            		}
            	}else{
            		newGame(0,0,unlock.getLevel()+1);
            	}
            	
            	
            }
        });
        
        //printActiveThreads();

        /*if(!runningBar){
        	button.setText("Calculating Score...");
            button.setEnabled(false);
        	new LevelOverTask().execute(startExperience);
        }*/

        Thread background = new Thread (new Runnable() {
        int level = startLevel;
        int exp = returnLevelExp(level);
        int percentage;
        String textTochangeLevel = "";
        TestActivity active = new TestActivity();
        public void run() {
        	
        		
        		percentage = (int)((returnLevelExp(level+1) - returnLevelExp(level)) * (((float)progress.getProgress()/(float)100)));

        		//System.out.println("In bar loop");
				// enter the code to be run while displaying the progressbar.
				//
				// This example is just going to increment the progress bar:
				// So keep running until the progress value reaches maximum value
				while (exp+percentage<endExperience) {
	        		//System.out.println("In bar loop");
				    // wait 500ms between each update
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				    if(progress.getProgress()>=100){
				    	level++;
				    	exp = returnLevelExp(level);
				    	progress.setProgress(0);
				    }
				    // active the update handler
				    //System.out.println(percentage + "%");
				    progress.incrementProgressBy(1);
				    percentage = (int)((returnLevelExp(level+1) - returnLevelExp(level)) * (((float)progress.getProgress()/(float)100)));
				    
				    textTochangeLevel = "Dungeon Hunter Level: " + level + "\nExp: " + (exp + percentage) + "/" + (returnLevelExp(calculateLevel((exp + percentage))+1));
				    active.receiveMyMessage(textTochangeLevel, findViewById(R.id.textinfoc), R.id.textinfoc);
				    
				}
				textTochangeLevel = "Dungeon Hunter Level: " + level + "\nExp: " + (endExperience) + "/" + (returnLevelExp(calculateLevel(endExperience)+1));
				active.receiveMyMessage(textTochangeLevel, findViewById(R.id.textinfoc), R.id.textinfoc);
				active.enableButton(findViewById(R.id.continue_button), R.id.continue_button);
            }
         });
        
        button.setText("Calculating Score...");
        button.setEnabled(false);
        background.start();
	}
	
	public class TestActivity extends Activity {
	    // Handler gets created on the UI-thread
	    private Handler mHandler = new Handler();
	    // This gets executed in a non-UI thread:
	    public void receiveMyMessage(String Msg,View v,int viewID) {
	        final String str = Msg;
	        final float msgScale = (int) Math.ceil(width/21);
	        if(v != null){
	        	View parent = (View) v.getParent();
	        	//View parent = (View) v;
	        	final TextView textField = (TextView) parent.findViewById(viewID);
	        	//final TextView textField = (TextView) v;
	        	mHandler.post(new Runnable() {
	            	public void run() {
	                	// This gets executed on the UI thread so it can safely modify Views
	            		textField.setTextSize((msgScale*(float).55));
	            		textField.setTextColor(Color.YELLOW);
	            		textField.setText(str);
	            	}
	        	});
	        }
	    }
	    public void enableButton(View v,int viewID) {
	    	if(v != null){
	        View parent = (View) v.getParent();
	        final Button button = (Button) parent.findViewById(viewID);
	        mHandler.post(new Runnable() {
	            public void run() {
	                // This gets executed on the UI thread so it can safely modify Views
	            	if(playerStats.checkBoss && gauntletLevel != 0 && gauntletLevel != 14){
	            		button.setText("Next Level");
	            	}
	            	else{
	            		button.setText("Continue");
	            	}
	            	button.setEnabled(true);
	            	//System.out.println(str);
	            }
	        });
	    	}
	    }
		public void endGame(ClassGameStats playerStats) {
			// TODO Auto-generated method stub
			
		}
	}
	
	public static <T> T[] concatenateArrays(T[] first, T[] second) {
		  T[] result = Arrays.copyOf(first, first.length + second.length);
		  System.arraycopy(second, 0, result, first.length, second.length);
		  return result;
		}
	
	class choiceClass{
		int choice;
		choiceClass(int choice){
			this.choice = choice;
		}
		public void setChoice(int choice){
			this.choice = choice;
		}
		public int getChoice(){
			return choice;
		}
	}
	
	public String compileEnemyData(int enemy){
		String holder = "";
		
		holder += "Base Health: " + (Draws.enemyBaseStats[enemy][0])*10 + "%\n";
		holder += "Base Attack: " + (Draws.enemyBaseStats[enemy][1])*10 + "%\n";
		if(enemy!=0){
			holder += "Starting Lives: " + Draws.enemyBaseStats[enemy][2] + "\n";
		}else{
			holder += "Starting Lives: Same as level\n";
		}
		
		holder += "\nModifiers\n";
		
		if(Draws.enemyAbilityStats[enemy][0]){holder += "Mana Burn; ";}
		if(Draws.enemyAbilityStats[enemy][1]){holder += "Poison; ";}
		if(Draws.enemyAbilityStats[enemy][2]){holder += "25% Magic Resistance; ";}
		if(Draws.enemyAbilityStats[enemy][3]){holder += "50% Magic Resistance; ";}
		if(Draws.enemyAbilityStats[enemy][4]){holder += "25% Physical Resistance; ";}
		if(Draws.enemyAbilityStats[enemy][5]){holder += "50% Physical Resistance; ";}
		if(Draws.enemyAbilityStats[enemy][6]){holder += "Amnesia; ";}
		if(Draws.enemyAbilityStats[enemy][7]){holder += "Blind; ";}
		if(Draws.enemyAbilityStats[enemy][8]){holder += "Weakness; ";}
		if(Draws.enemyAbilityStats[enemy][9]){holder += "Magical Attack; ";}
		if(Draws.enemyAbilityStats[enemy][10]){holder += "Undead; ";}
		if(Draws.enemyAbilityStats[enemy][11]){holder += "Coward; ";}
		if(Draws.enemyAbilityStats[enemy][12]){holder += "Banish; ";}
		if(Draws.enemyAbilityStats[enemy][13]){holder += "First Strike; ";}
		if(Draws.enemyAbilityStats[enemy][14]){holder += "Static; ";}
		
		return holder;
	}
	
	public String compileRituals(int god){
		String holder = "";
		holder += "Cost " + Draws.ritualLevels[god][0]*10 + " Piety: "+ Draws.ritualDescriptions[god][2] +"\n";
		holder += "Cost " + Draws.ritualLevels[god][1]*10 + " Piety: "+ Draws.ritualDescriptions[god][3] + "\n";
		holder += "Cost " + Draws.ritualLevels[god][2]*10 + " Piety: "+ Draws.ritualDescriptions[god][4] + "\n";
		return holder;
	}

	public int returnClassPoints(int level){
		switch(level){
			case 0:return 1;
			case 1:return 3;
			case 2:return 4;
			case 3:return 5;
			case 4:return 6;
			case 5:return 7;
			case 6:return 8;
			case 7:return 9;
			case 8:return 10;
			case 9:return 11;
			case 10:return 12;
			case 11:return 13;
			case 12:return 14;
			case 13:return 15;
			case 14:return 15;
			case 15:return 1;
			default:return 15;
		}
	}
	
	public int returnLevel(){
		int level=0;
		int count = 0;
		
		for(;level<Draws.levelStrings.length+1;level++){
			for(int place = 0;place<Draws.unlockLevels.length;place++){
				if(Draws.unlockLevels[place] < level){
					//System.out.println(Draws.classStrings[place] + "\nLevel: " + level + "\n");
					if(database.returnCompleted(0
							,place
        				  ,level,database,Draws)){
						//System.out.println("failed\n");
						//return level - 1;
						count++;
					}else{
						//System.out.println("passed\n");
					}
				}
			}
			if(count < returnClassPoints(level)){
				return (level -1) + settings[1];
			}
			count = 0;
		}
        return level + settings[1];
	}
	
	public int returnLevelCount(int level){
		int count = 0;
		for(int place = 0;place<Draws.unlockLevels.length;place++){
			if(Draws.unlockLevels[place] < level){

				if(database.returnCompleted(0
						,place
    				  ,level,database,Draws)){

					count++;
				}
			}
		}
		return returnClassPoints(level) - count;
	}
	
	public String[] mixupAdvice(String[] advice){
		Random random = new Random(System.currentTimeMillis());
		String holder = "";
		int switch1,switch2;
		for(int i = 0 ; i < advice.length;i++){
			switch1 = random.nextInt( advice.length );
			switch2 = random.nextInt( advice.length );
			while(switch2==switch1){
				switch2 = random.nextInt( advice.length );
			}
			holder = advice[switch1];
			advice[switch1] = advice[switch2];
			advice[switch2] = holder;
		}
		return advice;
	}
	
	public String returnProgressMarquee(int level){
		int neededClasses = returnLevelCount(level+1);
		String[] advice;
		switch(randomNumber(3)){
			case 0:advice = mixupAdvice(Draws.helpfulTips);break;
			case 1:advice = mixupAdvice(Draws.helpfulTips2);break;
			case 2:advice = mixupAdvice(Draws.helpfulTips3);break;
			default:advice = mixupAdvice(Draws.helpfulTips);break;
		}
		String holder = "";
		holder+="Beat the "+ Draws.levelStrings[level+1] + " level with "+ neededClasses +" more class";
		if (neededClasses>1){
			holder+="es";
		}
		holder+=" to unlock the next tier of characters. \t\t\t";
		
		for (int i = 0; i < advice.length;i++){
			holder+= advice[i];
			holder+="\t\t\t";
		}
		
		return holder;
		
	}
	
	public int determineTextSize(TextView box, String text){
		int tvWidth = box.getWidth();
		int smallestText = 5;
		boolean sizeFound = false;
		TextPaint textPaintClone = new TextPaint();
	    textPaintClone.set(box.getPaint());
	    textPaintClone.setTextSize(smallestText); 
		while(!sizeFound){
			if(textPaintClone.measureText(text) < tvWidth){
				smallestText++;
				textPaintClone.setTextSize(smallestText); 
			}else{
				sizeFound = true;
				smallestText-=2;
			}
		}
		return smallestText;
	}
	
	public void newGame(int pos1, int pos2, int pos3){

		final Context gameContext = this;
		//System.out.println("NewGame");
		if(backgroundMusic.running && backgroundMusic.currentlyPlaying != -1){
			backgroundMusic.stopBackground();
		}
		if(!backgroundMusic.running){
			backgroundMusic.setBackgoundNoiseTheme();
			backgroundMusic.playBackground();
		}
		
		//background.playBackgroundMain();
		//loadPlayer(R.raw.boss_kill);
		gauntletLevel = 0;
    	setContentView(R.layout.wheel);

    	//System.out.println("Here");
    	
        final TextView text1 = (TextView) findViewById(R.id.textida);
        final TextView text2 = (TextView) findViewById(R.id.textidb);
        final TextView text3 = (TextView) findViewById(R.id.textidc);
        final TextView text4 = (TextView) findViewById(R.id.textidd);
        final TextView text5 = (TextView) findViewById(R.id.textide);
        final TextView text6 = (TextView) findViewById(R.id.textidf);
        
        //System.out.println("Here");

        final ImageView completedPic = (ImageView) findViewById(R.id.completedPic);
        final ImageView completedPic2 = (ImageView) findViewById(R.id.completedPic2);
        final ImageView completedPic3 = (ImageView) findViewById(R.id.completedPic3);
        //final TextView text7 = (TextView) findViewById(R.id.textidg);
        
        ((Gallery) findViewById(R.id.gallery1)).setAdapter(new ImageAdapter(this,R.id.gallery1));
        ((Gallery) findViewById(R.id.gallery2)).setAdapter(new ImageAdapter(this,R.id.gallery2));
        ((Gallery) findViewById(R.id.gallery3)).setAdapter(new ImageAdapter(this,R.id.gallery3));
        
        //text1.setTextSize((scale.getScale()*(float).75));
        //text3.setTextSize((scale.getScale()*(float).70));
        //text5.setTextSize((scale.getScale()*(float).75));
        
        //text2.setTextSize(((scale.getScale())*(float).40));
        //text4.setTextSize(((scale.getScale())*(float).28));
        //text6.setTextSize(((scale.getScale())*(float).32));
        
        final TextView marquee1 = (TextView) findViewById(R.id.marqueetext);
        marquee1.setSelected(true);
        marquee1.setText(returnProgressMarquee(unlock.getLevel()));
        //text7.setTextSize(((scale)*(float).50));
        //database.printDatabase();
        //database.InsertTech("Knowledge", 0);
        
        Gallery g1 = (Gallery) findViewById(R.id.gallery1);
        g1.setAdapter(new ImageAdapter(this,R.id.gallery1));
        g1.setSelection(pos1);
        g1.setOnItemSelectedListener(new OnItemSelectedListener() 
        {
           public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
           {
        	    //text1.setTextSize(determineTextSize(text1,Draws.raceStrings[position]));
      	   		text1.setText(Draws.raceStrings[position]);
      	   		//text1.setTextSize(16+textScaler);
      	   		//text2.setTextSize(determineTextSize(text2,Draws.raceDescriptions[position]));
      	   		text2.setText(Draws.raceDescriptions[position]);
      	   		//text2.setTextSize(14+textScaler);
      	   		
      	   	//value.string = text1.toString();
      	   	//text1.setTextSize(TypedValue.COMPLEX_UNIT_PX, 25f);
      	   	//value.string = text2.toString();
      	   	//text2.setTextSize(TypedValue.COMPLEX_UNIT_PX, 17f);
              
      	   	if(!unlockAll){
                if(database.returnCompleted(
           				((Gallery) findViewById(R.id.gallery1)).getSelectedItemPosition()
           				,unlock.returnDescriptionClasses()[((Gallery) findViewById(R.id.gallery2)).getSelectedItemPosition()]
           				,((Gallery) findViewById(R.id.gallery3)).getSelectedItemPosition(),database,Draws)){
    	  			completedPic.setImageResource(R.drawable.check_yes);
    	  			completedPic2.setImageResource(R.drawable.check_yes);
    	  			completedPic3.setImageResource(R.drawable.check_yes);
      			}else{
	  				completedPic.setImageResource(R.drawable.check_no);
	  				completedPic2.setImageResource(R.drawable.check_no);
	  				completedPic3.setImageResource(R.drawable.check_no);
  				}
            	}else{
            		if(database.returnCompleted(
            				((Gallery) findViewById(R.id.gallery1)).getSelectedItemPosition()
            				,((Gallery) findViewById(R.id.gallery2)).getSelectedItemPosition()
            				,((Gallery) findViewById(R.id.gallery3)).getSelectedItemPosition(),database,Draws)){
     	  			completedPic.setImageResource(R.drawable.check_yes);
     	  			completedPic2.setImageResource(R.drawable.check_yes);
     	  			completedPic3.setImageResource(R.drawable.check_yes);
       			}else{
 	  				completedPic.setImageResource(R.drawable.check_no);
 	  				completedPic2.setImageResource(R.drawable.check_no);
 	  				completedPic3.setImageResource(R.drawable.check_no);
   				}
            	}
              //text7.setText(database.returnHighScores(((Gallery) findViewById(R.id.gallery1)).getSelectedItemPosition()
            	//	  ,((Gallery) findViewById(R.id.gallery2)).getSelectedItemPosition()
            	//	  ,((Gallery) findViewById(R.id.gallery3)).getSelectedItemPosition(),database,Draws));
           }

           public void onNothingSelected(AdapterView<?> arg0) {
        	   // Auto-generated method stub
			
           }
        });
        Gallery g2 = (Gallery) findViewById(R.id.gallery2);
        g2.setAdapter(new ImageAdapter(this,R.id.gallery2));
        g2.setSelection(pos2);
        g2.setOnItemSelectedListener(new OnItemSelectedListener() 
        {
           public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
           {
        	   if(!unlockAll){

        		   //text3.setTextSize(determineTextSize(text3,Draws.classStrings[unlock.returnDescriptionClasses()[position]]));
        		   text3.setText(Draws.classStrings[unlock.returnDescriptionClasses()[position]]);
        		   //text4.setTextSize(determineTextSize(text4,Draws.classDescriptions[unlock.returnDescriptionClasses()[position]]));
        		   text4.setText(Draws.classDescriptions[unlock.returnDescriptionClasses()[position]]);
       	   		}else{
       	   			//text3.setTextSize(determineTextSize(text3,Draws.classStrings[position]));
       	   			text3.setText(Draws.classStrings[position]);
       	   			//text4.setTextSize(determineTextSize(text4,Draws.classDescriptions[position]));
       	   			text4.setText(Draws.classDescriptions[position]);
       	   		}
        	   //text3.setTextSize(16+textScaler);
        	   //text4.setTextSize((11-(text4.getText().length())/26)+textScaler);
        	   
        	   //value.string = text3.toString();
         	   	//text3.setTextSize(TypedValue.COMPLEX_UNIT_PX, 25f);
         	   	//value.string = text4.toString();
         	   	//text4.setTextSize(TypedValue.COMPLEX_UNIT_PX, 17f);
        	   
        	   if(!unlockAll){
                   if(database.returnCompleted(
              				((Gallery) findViewById(R.id.gallery1)).getSelectedItemPosition()
              				,unlock.returnDescriptionClasses()[((Gallery) findViewById(R.id.gallery2)).getSelectedItemPosition()]
              				,((Gallery) findViewById(R.id.gallery3)).getSelectedItemPosition(),database,Draws)){
       	  			completedPic.setImageResource(R.drawable.check_yes);
       	  			completedPic2.setImageResource(R.drawable.check_yes);
       	  			completedPic3.setImageResource(R.drawable.check_yes);
         			}else{
   	  				completedPic.setImageResource(R.drawable.check_no);
   	  				completedPic2.setImageResource(R.drawable.check_no);
   	  				completedPic3.setImageResource(R.drawable.check_no);
     				}
               	}else{
               		if(database.returnCompleted(
               				((Gallery) findViewById(R.id.gallery1)).getSelectedItemPosition()
               				,((Gallery) findViewById(R.id.gallery2)).getSelectedItemPosition()
               				,((Gallery) findViewById(R.id.gallery3)).getSelectedItemPosition(),database,Draws)){
        	  			completedPic.setImageResource(R.drawable.check_yes);
        	  			completedPic2.setImageResource(R.drawable.check_yes);
        	  			completedPic3.setImageResource(R.drawable.check_yes);
          			}else{
    	  				completedPic.setImageResource(R.drawable.check_no);
    	  				completedPic2.setImageResource(R.drawable.check_no);
    	  				completedPic3.setImageResource(R.drawable.check_no);
      				}
               	}
           }

           public void onNothingSelected(AdapterView<?> arg0) {
        	   // Auto-generated method stub
			
           }
        });   
        Gallery g3 = (Gallery) findViewById(R.id.gallery3);
        g3.setAdapter(new ImageAdapter(this,R.id.gallery3));
        g3.setSelection(pos3);
        g3.setOnItemSelectedListener(new OnItemSelectedListener() 
        {
           public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
           {
        	   //if(!unlockAll){
        		//   text5.setText(Draws.levelStrings[Draws.returnDescriptionPointers(level)[position]]);
        		//   text6.setText(Draws.levelDescriptions[Draws.returnDescriptionPointers(level)[position]]);
        	   //}else{
        	       //text5.setTextSize(determineTextSize(text5,Draws.levelStrings[position]));
        		   text5.setText(Draws.levelStrings[position]);
        		   //text5.setTextSize(16+textScaler);
        		   //text6.setTextSize(determineTextSize(text6,Draws.levelDescriptions[position]));
                   text6.setText(Draws.levelDescriptions[position]);
                   //text6.setTextSize((10-(Draws.classDescriptions[position].length())/35)+textScaler);
                   
                   //value.string = text5.toString();
             	   	//text5.setTextSize(TypedValue.COMPLEX_UNIT_PX, 25f);
             	   	//value.string = text6.toString();
             	   	//text6.setTextSize(TypedValue.COMPLEX_UNIT_PX, 17f);
        	   //}
                   
                   if(!unlockAll){
                       if(database.returnCompleted(
                  				((Gallery) findViewById(R.id.gallery1)).getSelectedItemPosition()
                  				,unlock.returnDescriptionClasses()[((Gallery) findViewById(R.id.gallery2)).getSelectedItemPosition()]
                  				,((Gallery) findViewById(R.id.gallery3)).getSelectedItemPosition(),database,Draws)){
           	  			completedPic.setImageResource(R.drawable.check_yes);
           	  			completedPic2.setImageResource(R.drawable.check_yes);
           	  			completedPic3.setImageResource(R.drawable.check_yes);
             			}else{
       	  				completedPic.setImageResource(R.drawable.check_no);
       	  				completedPic2.setImageResource(R.drawable.check_no);
       	  				completedPic3.setImageResource(R.drawable.check_no);
         				}
                   	}else{
                   		if(database.returnCompleted(
                   				((Gallery) findViewById(R.id.gallery1)).getSelectedItemPosition()
                   				,((Gallery) findViewById(R.id.gallery2)).getSelectedItemPosition()
                   				,((Gallery) findViewById(R.id.gallery3)).getSelectedItemPosition(),database,Draws)){
            	  			completedPic.setImageResource(R.drawable.check_yes);
            	  			completedPic2.setImageResource(R.drawable.check_yes);
            	  			completedPic3.setImageResource(R.drawable.check_yes);
              			}else{
        	  				completedPic.setImageResource(R.drawable.check_no);
        	  				completedPic2.setImageResource(R.drawable.check_no);
        	  				completedPic3.setImageResource(R.drawable.check_no);
          				}
                   	}
           }

           public void onNothingSelected(AdapterView<?> arg0) {
        	   // Auto-generated method stub
			
           }
        });  
        
        final Button button = (Button) findViewById(R.id.info_button);
        final Button button2 = (Button) findViewById(R.id.start_button);
        
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	
            	Intent i = new Intent(gameContext, ActivityShop.class);
            	startActivity(i);
            	
            }
        });
        
        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	if(((Gallery) findViewById(R.id.gallery3)).getSelectedItemPosition() == 15){
            		Random random = new Random(System.currentTimeMillis());
            		final int playerRace = random.nextInt( Draws.raceStrings.length );
            		final int playerClass = random.nextInt( Draws.classStrings.length );
            		//System.out.println(playerRace + " : " + playerClass + " : " + gauntletLevel);
            		playerStats = new 
        					ClassGameStats(
        							(width/(numTiles+1)),
        							playerRace,
        							playerClass,
        							++gauntletLevel, dataBaseInfo,sounds,unlock.getLevel()+1,difficultySetting);
            		//setContentView(new Panel(gameContext));
            		//i.putExtra("scale", scale.getScale());
    	    		//i.putExtra("scale", numTiles);
                    //i.putExtra("player", playerStats);
                    activityFunction(gameContext);
            	}else{
            		if(!unlockAll){
            			playerStats = new 
            					ClassGameStats(
            							(width/(numTiles+1)),
            							((Gallery) findViewById(R.id.gallery1)).getSelectedItemPosition(),
            							unlock.returnDescriptionClasses()[((Gallery) findViewById(R.id.gallery2)).getSelectedItemPosition()],
            							((Gallery) findViewById(R.id.gallery3)).getSelectedItemPosition(), dataBaseInfo,sounds,unlock.getLevel()+1,difficultySetting);

            		}else{
            			playerStats = new 
                    		ClassGameStats(
                    		(width/(numTiles+1)),
                    		((Gallery) findViewById(R.id.gallery1)).getSelectedItemPosition(),
                    		((Gallery) findViewById(R.id.gallery2)).getSelectedItemPosition(),
                    		((Gallery) findViewById(R.id.gallery3)).getSelectedItemPosition(), 
                    		dataBaseInfo,sounds,unlock.getLevel()+1,difficultySetting);

            	}
                //setContentView(new Panel(gameContext));
    	    	//i.putExtra("scale", scale.getScale());
	    		//i.putExtra("scale", numTiles);
                //i.putExtra("player", playerStats);
    	    	//System.out.println("Got Here");
    	    	activityFunction(gameContext);
            	}
            }
        });
	}
	
	/*public class GameActivity extends Activity {
	    // Handler gets created on the UI-thread
	    private Handler mHandler = new Handler();
	    // This gets executed in a non-UI thread:
	    gameStats playerStats;
	    GameActivity(gameStats playerStats){
	    	this.playerStats = playerStats;
	    }
	    public void buildContent(Context sentContext) {
	    	final Context gameContext = sentContext;
	        mHandler.post(new Runnable() {
	            public void run() {
	                //setContentView(new Panel(gameContext));
	            	activityFunction(gameContext);
	            }
	        });
	    }
	}*/
	
	public void activityFunction(Context gameContext){
		//This function was made to pass the player class back and forth between 
		if(backgroundMusic.running){
  			backgroundMusic.stopBackground();
  		}
		
		if(playerStats.player_level == 0){
			playerStats.player_race = 0;
			playerStats.player_class = 14;
		}
		playerStats.unlockedCharacters=(settings[1]==1)?true:false;
		//Creating global vars like this is bad. Dont do this.
		passedPlayerStats = playerStats;
		bkVolume = backgroundMusic.getVolume();
		setContentView(R.layout.loadingscreen);
		Intent i = new Intent(gameContext, ActivityGamePanel.class);
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivityForResult(i,1);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    //System.out.println(requestCode + " " + resultCode + " " + data);
	    //switch(requestCode) {
	    //case (1) : {
	      //if (resultCode == Activity.RESULT_OK) {
	    if(database.levelPlayed()){
	    	//Log.d("WinBug","After Return");
	    	//returnedWithResults = true;
	    	new AsyncReturnGameData().execute(data);
	    	//Log.d("WinBug","After Async");
	    	//infoMenu();
	    }else{
			if(!unlockAll && playerStats != null){
				newGame(playerStats.player_race, 
						unlock.returnNewGamePositionClasses(unlock.returnDescriptionClasses(),playerStats.player_class), 
						unlock.getLevel()+1);
			}else if (playerStats != null){
				newGame(playerStats.player_race, playerStats.player_class, playerStats.player_level);
			}else{
				newGame(0,0,unlock.getLevel()+1);
			}
	    }
	      //}
	     // break;
	      
	   // } 
	  //}
	}
	
	private class AsyncReturnGameData extends AsyncTask<Intent, Void, ClassResultHolder>{
		
		  @Override
	      protected void onPreExecute(){
	            // show your progress dialog

	      }

	      @Override
	      protected void onPostExecute(ClassResultHolder results){
	    	  infoMenu();
	      }

		@Override
		protected ClassResultHolder doInBackground(Intent... params) {
			//Bundle extras = params[0].getExtras();
			//System.out.println(extras);
			//Log.d("WinBug","Before Load");
			// TODO Auto-generated method stub
			//return results;
			return null;
		}

	   }
	
	public ClassGameStats restartLevel(int prace, int pclass, int plevel, int difficulty){
		ClassGameStats funcStats = new ClassGameStats((width/(numTiles+1)),prace,pclass,plevel, dataBaseInfo,sounds,unlock.getLevel()+1,difficulty);
		return funcStats;
	}
	
	public void initializeSeekBar(SeekBar seekBar, final TextView text){
			seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {       
    	    public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {     
    	        // TODO Auto-generated method stub      
    	    	/*if(text == findViewById(R.id.tiletext2)){
    	    		text.setText(""+(progress+15));
    	    	}
    	    	else*/ if(text == findViewById(R.id.difftext2)){
    	    		text.setText(""+(progress+50) +" %");
    	    	}
    	    	else{
    	    		text.setText(""+progress);
    	    	}

    	    }

			public void onStartTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}       
    	}); 
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.new_game:
	    	if (playerStats != null){
	    		if(!unlockAll){
	    			newGame(playerStats.player_race, 
        					unlock.returnNewGamePositionClasses(unlock.returnDescriptionClasses(),playerStats.player_class), 
        					unlock.getLevel()+1);
        		}else{
        			newGame(playerStats.player_race, playerStats.player_class, playerStats.player_level);
        		}
        	}else{
        		newGame(0,0,unlock.getLevel()+1);
        	}
	        return true;
	    case R.id.info:
	    	if(playerStats != null){
	    		playerStats = restartLevel(playerStats.player_race,playerStats.player_class,playerStats.player_level, playerStats.difficulty);
	    		final Context gameContext = this;
	    		//Intent i = new Intent(gameContext, gamePanel.class);
	    		//i.putExtra("scale", scale.getScale());
	    		//i.putExtra("scale", numTiles);
            	//i.putExtra("player", playerStats);
	    		//System.out.println("Got Here");
	    		activityFunction(gameContext);
            	//startActivity(i);
            	//playerStats = gamePanel.passedPlayerStats;
            	
	    	}
	        //showInfo();
	        return true;
	    case R.id.settings:
	    	//unlockAll = !unlockAll;
	    	//final View myView = (View)findViewById(R.layout.settingsmenu);
	    	//final ViewGroup vg = (ViewGroup)(new View(this));
	    	//vg.removeView(myView);
            if(backgroundMusic.running){
            	backgroundMusic.stopBackground();
            }
	    	setContentView(R.layout.settingsmenu);
	    	final Button button = (Button) findViewById(R.id.settingsSave);
	    	final Button button2 = (Button) findViewById(R.id.settingsCancel);
	    	//final SeekBar tileNumber = (SeekBar) findViewById(R.id.tileNumber);
	    	final SeekBar difficulty = (SeekBar) findViewById(R.id.difficulty);
	    	final SeekBar bkmusic = (SeekBar) findViewById(R.id.bkmusic);
	    	final SeekBar soundfx = (SeekBar) findViewById(R.id.soundfx);
	    	
	    	//TextView tileText = (TextView) findViewById(R.id.tiletext2);
	    	TextView diffText = (TextView) findViewById(R.id.difftext2);
	    	TextView bkText = (TextView) findViewById(R.id.bktext2);
	    	TextView sfxText = (TextView) findViewById(R.id.sfxtext2);
	    	
	    	//tileText.setTextSize((scale.getScale()*(float).90));
	    	//diffText.setTextSize((scale.getScale()*(float).90));
	    	//bkText.setTextSize((scale.getScale()*(float).90));
	    	//sfxText.setTextSize((scale.getScale()*(float).90));
	    	
	    	//tileNumber.setMax(35);
	    	difficulty.setMax(100);
	    	bkmusic.setMax(100);
	    	soundfx.setMax(100);
	    	//if(unlock.getLevel() < 14){
	    	//	tileNumber.setEnabled(false);
	    	//}else{
	    	//	tileNumber.setEnabled(true);
	    	//}
	    	
	    	//tileNumber.setProgress(settings[4]-15);
	    	difficulty.setProgress(settings[5]);
	    	difficulty.setEnabled(false);
	    	bkmusic.setProgress((int)(settings[6]));
	    	soundfx.setProgress((int)(settings[7])); 
	    	
	    	//tileText.setText("" + (settings[4]));
	    	diffText.setText(""+(settings[5]+50) +" %");
	    	bkText.setText("" +(int)(settings[6]));
	    	sfxText.setText("" + (int)(settings[7]));
	    	
	    	//initializeSeekBar(tileNumber,tileText);
	    	initializeSeekBar(difficulty,diffText);
	    	initializeSeekBar(bkmusic,bkText);
	    	initializeSeekBar(soundfx,sfxText);
	    	
	    	
	        button.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	            //	Log.d("PROGRESS",""+(15+tileNumber.getProgress()));
	            //	Log.d("PROGRESS",""+bkmusic.getProgress());
	            //	Log.d("PROGRESS",""+soundfx.getProgress());
	            //	numTiles = 15+tileNumber.getProgress();
	            	difficultySetting = difficulty.getProgress();
	            	backgroundMusic.setVolume(bkmusic.getProgress());
	            	sounds.setVolume(soundfx.getProgress());
	            	
	    	    	database.InsertDatabase(0, 0, 0, 0, numTiles, difficultySetting, (int) backgroundMusic.getVolume(), (int) sounds.getVolume());
	        		settings = database.returnScoreValues(0, -1, -1);
	            	
	                //((ViewManager)myView.getParent()).removeView(myView);
	            	if (playerStats != null){
	            		if(!unlockAll){
	            			newGame(playerStats.player_race, 
	            					unlock.returnNewGamePositionClasses(unlock.returnDescriptionClasses(),playerStats.player_class), 
	            					unlock.getLevel()+1);
	            		}else{
	            			newGame(playerStats.player_race, playerStats.player_class, playerStats.player_level);
	            		}
	            	}else{
	            		newGame(0,0,unlock.getLevel()+1);
	            	}
	            	}
	            }
	        );
	        button2.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	                //((ViewManager)myView.getParent()).removeView(myView);
	            	if (playerStats != null){
	            		if(!unlockAll){
	            			newGame(playerStats.player_race, 
	            					unlock.returnNewGamePositionClasses(unlock.returnDescriptionClasses(),playerStats.player_class), 
	            					unlock.getLevel()+1);
	            		}else{
	            			newGame(playerStats.player_race, playerStats.player_class, playerStats.player_level);
	            		}
	            	}else{
	            		newGame(0,0,unlock.getLevel()+1);
	            	}
	            	}
	            }
	        );
	    	//unlockAll = !unlockAll;
        	//newGame(0,0,unlock.getLevel()+1);	
	        //newSettings();
	        return true;
	    case R.id.quit:
	    	finish();
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	
	public class ImageAdapter extends BaseAdapter {
        /** The parent context */
        private Context myContext;
        private int myview;
        
        /** Simple Constructor saving the 'parent' context. */
        public ImageAdapter(Context c, int v) { this.myContext = c; this.myview = v;}
 
        /** Returns the amount of images we have defined. */
        public int getCount() { 
        	
        	//View vg = getCurrentFocus().findFocus();
        	//System.out.println(this.getView(0, null, null));
        	//this.getView(0, null, null);
        	if (myview == R.id.gallery1){
        		if (!unlockAll){
        			return unlock.returnRaceCount();
        		}else{
        			return Draws.raceImages.length;
        		}
        	}else if(myview == R.id.gallery2){
        		if (!unlockAll){
        			return unlock.returnClassCount();
        		}else{
        			return Draws.classImages.length;
        		}
        	}else{
        		if (!unlockAll){
        			return unlock.returnLevelCount();
        		}else{
        			return Draws.levelImages.length;
        		}
        	}
        	
        }
        
        /* Use the array-Positions as unique IDs */
        public Object getItem(int position) { return position; }
        //Returns the positions of the items selected
        public long getItemId(int position) { return position; }
        
        /** Returns a new ImageView to
         * be displayed, depending on
         * the position passed. */
        public View getView(int position, View convertView, ViewGroup parent) {
        	//Display display = getWindowManager().getDefaultDisplay();
            /*ImageView i = new ImageView(this.myContext);
 
            i.setImageResource(this.myImageIds[position]);
            //Image should be scaled as width/height are set.
            //i.setScaleType(ImageView.ScaleType.FIT_XY);
            i.setScaleType(ImageView.ScaleType.FIT_START);
            //Set the Width/Height of the ImageView.
            i.setLayoutParams(new Gallery.LayoutParams(75, 75));
            return i;*/
            
        	//View w = getCurrentFocus();
        	//System.out.println(parent);
        	//System.out.println((Gallery) findViewById(R.id.gallery1));
        	
            View v;

			// just a simple optimiztaion -
			// we only inflate a new layout if we don't have one to reuse

			if (convertView == null)
				v = LayoutInflater.from(this.myContext).inflate(R.layout.imgdesc,
					parent, false);
			else
				v = convertView;
			
			// Now that we have our new custom View, find out widgets in the
			// view and set them
			ImageView iv = (ImageView) v.findViewById(R.id.imageview); 
			if (myview == R.id.gallery1){
				iv.setImageResource(Draws.raceImages[position]);
			}else if(myview == R.id.gallery2){
				if (!unlockAll){
					iv.setImageResource(unlock.returnUnlockedClasses()[position]);
				}else
				{
					iv.setImageResource(Draws.classImages[position]);
					//iv.setImageBitmap(dScaler[0].graphicScaled[position]);
				}
			}else{
				iv.setImageResource(Draws.levelImages[position]);
			}
			//iv.setScaleType(ImageView.ScaleType.FIT_START);
			
			if(!unlockAll){
				switch(myview){
				case R.id.gallery2:
					if(!unlock.getClassUsed(unlock.returnUnlockedClassNumbers()[position])){
						TextView tv = (TextView) v.findViewById(R.id.textview);
						tv.setTextColor(Color.YELLOW);
						tv.setText("New");
					}
					break;
				case R.id.gallery3:
					if(position == 0){
						TextView tv = (TextView) v.findViewById(R.id.textview);
						tv.setTextColor(Color.YELLOW);
						tv.setText("Tutorial");
					}
					else if(!unlock.getLevelUsed(position)){
						TextView tv = (TextView) v.findViewById(R.id.textview);
						tv.setTextColor(Color.YELLOW);
						tv.setText("New");
					}
				break;
				}
			}
			//This adds the text underneath the pictures. Removed because it is distracting
			
			//TextView tv = (TextView) v.findViewById(R.id.textview);
			//if (myview ==  R.id.gallery1){
			//	tv.setText(Draws.raceStrings[position]);
			//}else if(myview ==  R.id.gallery2){
			//	tv.setText(Draws.classStrings[position]);
			//}else{
			//	tv.setText(Draws.levelStrings[position]);
			//}
			int multiple = 20 + (int)Math.pow((int)(((float)point.x)/240),2)*22;
			v.setLayoutParams(new Gallery.LayoutParams(multiple, 75));
			if(point.x<360){
				iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
			}else{
				iv.setScaleType(ImageView.ScaleType.FIT_START);
			}
			//v.setLayoutParams(new Gallery.LayoutParams(100, 75));
			
			//getResources().getResourceEntryName(R.string.app_name)
			
			return v;
             

            
        }
 
        /** Returns the size (0.0f to 1.0f) of the views
         * depending on the 'offset' to the center. */
        public float getScale(boolean focused, int offset) {
                /* Formula: 1 / (2 ^ offset) */
            return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
        }
    }
}
